﻿using System;
using System.Diagnostics;

namespace PerformanceCounterTestApp
{
    public class CreatePermanceInfoObject
    {
        static int counter = 0;
        static string myCategory = "Mark S Performance Counter";
        static string myCounter1 = "Process Time";
        static string myCounter2 = "No of processes";
        static string myCounter3 = "Random";

        static public string CategoryName
        {
            get { return myCategory; }
        }

        public CreatePermanceInfoObject()
        {
            if (counter++ == 0)
                CreateMyPerformanceCounter();
        }

        private void CreateMyPerformanceCounter()
        {
            if (PerformanceCounterCategory.Exists(myCategory))
                return;
            CounterCreationDataCollection cd = new CounterCreationDataCollection();
            cd.Add(new CounterCreationData(myCounter1, "Elapsed time since program start in milli seconds",
                PerformanceCounterType.NumberOfItems32));

            cd.Add(new CounterCreationData(myCounter2, "Number of system processes",
                PerformanceCounterType.NumberOfItems32));

            cd.Add(new CounterCreationData(myCounter3, "Random Value",
                PerformanceCounterType.NumberOfItems32));

            PerformanceCounterCategory.Create(
                myCategory,
                "Test category for showing the usage of self created performance counter objects",
                PerformanceCounterCategoryType.SingleInstance,
                cd);
        }

        public void GenerateNextValues()
        {
            TimeSpan diff = DateTime.Now - Process.GetCurrentProcess().StartTime;
            using (PerformanceCounter pc = new PerformanceCounter(myCategory, myCounter1, false))
            {
                pc.RawValue = (long)diff.TotalMilliseconds;
            }
            using (PerformanceCounter pc = new PerformanceCounter(myCategory, myCounter2, false))
            {
                pc.RawValue = Process.GetProcesses().Length;
            }
            using (PerformanceCounter pc = new PerformanceCounter(myCategory, myCounter3, false))
            {
                pc.RawValue = new Random(diff.Milliseconds).Next(20, 300);
            }
        }
    }
}
